<?php

function getMergedCOVAShape($scenarioid, $dbobj, $seglist) {
   $segs = "'" . join("','", $seglist) . "'";
   $dbobj->querystring = "  select asText(ST_union(simplify(poly_geom,0.0001))) as seg_geom from scen_model_element ";
   $dbobj->querystring .= " where ";
   if (strlen(trim($segs)) > 0) {
      $dbobj->querystring .= " custom2 in ($segs) ";
   } else {
      $dbobj->querystring .= " ( (custom2 = '') or (custom2 is null) ) ";
   }
   $dbobj->querystring .= " and scenarioid = $scenarioid and custom1 in ( 'cova_ws_container' , 'cova_ws_subnodal') ";
   //print("$dbobj->querystring ; <br>\n");
   $dbobj->performQuery();
   if ($dbobj->numrows > 0) {
      $shp = $dbobj->getRecordValue(1,'seg_geom');
      return $shp;
   } else {
      return false;
   }
}


function cova_graphFlowDuration($result_set, $debug) {
   global $session_db, $goutdir, $goutpath;
   $out = array('img_url'=>'', 'debug'=>'');
   $query = $result_set['query'];
   // create graph object to show bar graph comparisons of monthle median flow
   //$session_db->querystring = "select extract(month from thisdate) as thismo, median(\"Qout_0\") as qout0, median(\"Qout_2\") as qout2 from ($query) as foo group by thismo ";
   
   $color = array(0=>'blue',1=>'green',2=>'brown',3=>'red');
   $bgs = array();
   $ckey = 0;
   $i = 0;
   $ymax = 0.001;
   $ymin = 0.001;
   foreach ($result_set['valid_cols'] as $thiscol) {
      $cdel = ',';
      $session_db->querystring = "select extract(month from thisdate) as thismo, ";
      $session_db->querystring .= "\"$thiscol\" as \"$thiscol\" ";
      $cdel = ',';

      $session_db->querystring .= " from ($query) as foo ";
      $session_db->querystring .= " order by \"$thiscol\" DESC";

      $session_db->performQuery();
      if ($debug) {
         $out['debug'] .= "$session_db->querystring <br>";
      }
      $session_db->show = 0;
      $session_db->showList();
      $out['data_table'] .= $session_db->outstring . "<br>";

      $flowrecs = $session_db->queryrecords;
      $nums = count($flowrecs);
      $num = 0;
      foreach ($flowrecs as $key=>$thisrec) {
         $flow = $thisrec[$thiscol];
         if ($flow > $ymax) {
            $ymax = $flow;
         }
         if ( ($flow < $ymin) and ($flow > 0) ) {
            $ymin = $flow;
         }
         $ret = $num / $nums;
         $num++;
         $flowrecs[$key]["p_$thiscol"] = $ret;
      }
      //print("key:  $ckey<br>");
      $graph = array();
      $graph['graphrecs'] = $flowrecs;
      $graph['xcol'] = "p_$thiscol";
      $graph['ycol'] = "$thiscol";
      $graph['yaxis'] = 1;
      $graph['plottype'] = 'line';
      $ckey = $i;
      if (!isset($color[$ckey])) {
         $ckey = 0;
      }
      $i++;
      $graph['color'] = $color[$ckey];
      $graph['ylegend'] = $thiscol;
      $bgs[] = $graph;
   }

   $multibar = array(
      'title'=> ucwords($function) . " Monthly Flows",
      'xlabel'=>'Exceedance',
      'ylabel'=>'Flow (cfs)',
      'num_xlabels'=>15,
      'gwidth'=>600,
      'gheight'=>400,
      'overlapping'=>0,
      'labelangle'=>90,
      'randomname'=>0,
      'scale'=>'linlog',
      'ymin'=>$ymin,
      //'ymax'=>$ymax,
      'legendlayout'=>LEGEND_HOR,
      'legendpos'=>array(0.20,0.95,'left','bottom'),
      'base
name'=>"medflows_$elementid",
      'bargraphs'=>$bgs
   );
   $graphurl = showGenericMultiPlot($goutdir, $goutpath, $multibar, $debug);
   $out['img_url'] = $graphurl;
   return $out;
}


function cova_graphFlowComparison($result_set, $function, $debug, $minval = NULL, $digits = -1, $mode = 'monthly') {
   global $session_db, $goutdir, $goutpath;
   // $mode - daily - does the stat over the daily values of the month in question
   //   - monthly - computes the mean monthly, then applies the stat to that summary query
   $out = array('img_url'=>'', 'debug'=>'');
   $query = $result_set['query'];
   // create graph object to show bar graph comparisons of monthle median flow
   //$session_db->querystring = "select extract(month from thisdate) as thismo, median(\"Qout_0\") as qout0, median(\"Qout_2\") as qout2 from ($query) as foo group by thismo ";
   $cdel = ',';
   
   switch ($mode) {
   
      case 'daily':
         // just took a median monthly value, that is, the median value that appears in that month during the model period
         $finalquery = $query;
      break;

      case 'monthly':
         // takes the value for mean monthly flow during the modeling period
         $finalquery = " select * from ( ";
         $finalquery .= "    select extract(year from thisdate) as thisyear, "; 
         $finalquery .= "       extract(month from thisdate) as thismonth, "; 
         $finalquery .= "       min(thisdate) as thisdate "; 
         foreach ($result_set['valid_cols'] as $scol) {
            $finalquery .= ", ";
            $finalquery .= "       avg(\"$scol\") "; 
            $finalquery .= "       as \"$scol\" "; 
         }
         $finalquery .= "    from ($query) as foo "; 
         $finalquery .= "    group by extract(year from thisdate), extract(month from thisdate) "; 
         $finalquery .= " ) as bar ";
      break;
   
      default:
         // just took a median monthly value, that is, the median value that appears in that month during the model period
         $finalquery = $query;
      break;
   }

   // now aplpy the chosen stat to the final query
   $session_db->querystring = "select extract(month from thisdate) as thismo ";
   foreach ($result_set['valid_cols'] as $thiscol) {
      $session_db->querystring .= "$cdel  ";
      if ($digits >= 0) {
         $session_db->querystring .= "round(";
      }
      $session_db->querystring .= "$function(\"$thiscol\") ";
      if ($digits >= 0) {
         $session_db->querystring .= "::numeric, $digits) ";
      }
      $session_db->querystring .= " as \"$thiscol\" ";
      $cdel = ',';
   }
   $session_db->querystring .= " from ($finalquery) as foo ";
   if (!($minval === NULL)) {
      $firstcol = $result_set['valid_cols'][0];
      $session_db->querystring .= "WHERE \"$firstcol\" > $minval ";
   }
   $session_db->querystring .= " group by thismo order by thismo";

   $session_db->performQuery();
   if ($debug) {
      $out['debug'] .= "$session_db->querystring <br>";
   }
   $session_db->show = 0;
   $session_db->showList();
   $out['data_table'] .= $session_db->outstring . "<br>";
   $out['data_records'] .= $session_db->queryrecords . "<br>";
   $flowrecs = $session_db->queryrecords;
   
   $color = array('blue','green','brown','red');
   $bgs = array();
   foreach ($result_set['valid_cols'] as $key => $val) {
      $graph = array();
      $graph['graphrecs'] = $flowrecs;
      $graph['xcol'] = 'thismo';
      $graph['ycol'] = $val;
      $graph['yaxis'] = 1;
      $graph['plottype'] = 'bar';
      $graph['color'] = $color[$key];
      $graph['ylegend'] = $val;
      $bgs[] = $graph;
   }

   $multibar = array(
      'title'=> ucwords($function) . " Monthly Flows",
      'xlabel'=>'Month',
      'ylabel'=>'Flow (cfs)',
      'num_xlabels'=>15,
      'gwidth'=>600,
      'gheight'=>400,
      'overlapping'=>0,
      'labelangle'=>90,
      'randomname'=>0,
      'legendlayout'=>LEGEND_HOR,
      'legendpos'=>array(0.20,0.95,'left','bottom'),
      'base
name'=>"medflows_$elementid",
      'bargraphs'=>$bgs
   );
   $graphurl = showGenericMultiPlot($goutdir, $goutpath, $multibar, $debug);
   $out['img_url'] = $graphurl;
   return $out;
}


function cova_graphHabitatComparison($result_set, $function, $debug, $minval = NULL, $digits = -1, $gwidth = 600, $gheight = 400, $gname = 'habitat', $title = '') {
   global $session_db, $goutdir, $goutpath;
   $out = array('img_url'=>'', 'debug'=>'');
   $query = $result_set['query'];
   // create graph object to show bar graph comparisons of monthle median flow
   //$session_db->querystring = "select extract(month from thisdate) as thismo, median(\"Qout_0\") as qout0, median(\"Qout_2\") as qout2 from ($query) as foo group by thismo ";
   $cdel = ',';
   
   
   // just took a median monthly value, that is, the median value that appears in that month during the model period
   $function_parts = split(',',$function);
   $function = $function_parts[0];
   switch ($function) {
      case 'r_quantile':
         $fopen = 'r_quantile(array_accum(';
         $fclose = "), " . $function_parts[1] . ")";
      break;

      default:
         $fopen = $function . "(";
         $fclose = ")";
      break;
   }
   $session_db->querystring = "select extract(month from thisdate) as thismo ";
   foreach ($result_set['valid_cols'] as $thiscol) {
      $session_db->querystring .= "$cdel  ";
      if ($digits >= 0) {
         $session_db->querystring .= "round(";
      }
      $session_db->querystring .= "$fopen\"$thiscol\"$fclose ";
      if ($digits >= 0) {
         $session_db->querystring .= "::numeric, $digits) ";
      }
      $session_db->querystring .= " as \"$thiscol\" ";
      $cdel = ',';
   }
   $session_db->querystring .= " from ($query) as foo ";
   if (!($minval === NULL)) {
      $firstcol = $result_set['valid_cols'][0];
      $session_db->querystring .= "WHERE \"$firstcol\" > $minval ";
   }
   $session_db->querystring .= " group by thismo order by thismo";
   $session_db->performQuery();
   $out['debug'] .= "$session_db->querystring <br>";
   $session_db->show = 0;
   $session_db->showList();
   $out['data_table'] .= $session_db->outstring . "<br>";
   $flowrecs = $session_db->queryrecords;
   
   $color = array('blue','green','brown','red');
   $bgs = array();
   $legend_len = 0;
   foreach ($result_set['valid_cols'] as $key => $val) {
      $graph = array();
      $graph['graphrecs'] = $flowrecs;
      $graph['xcol'] = 'thismo';
      $graph['ycol'] = $val;
      $graph['yaxis'] = 1;
      $graph['plottype'] = 'bar';
      $graph['color'] = $color[$key];
      if (isset($result_set['legends'][$val])) {
         $graph['ylegend'] = $result_set['legends'][$val];
      } else {
         $graph['ylegend'] = $val;
      }
      $bgs[] = $graph;
   }
   if ($title == '') {
      $title = ucwords($function) . ' ' . $gname;
   }
   $multibar = array(
      'title'=> $title,
      'xlabel'=>$result_set['xlabel'],
      'ylabel'=>$result_set['ylabel'],
      'num_xlabels'=>15,
      'gwidth'=>$gwidth,
      'gheight'=>$gheight,
      'overlapping'=>0,
      'labelangle'=>90,
      'randomname'=>0,
      'legendlayout'=>LEGEND_HOR,
      'legendpos'=>array(0.5,0.90,'center','bottom'),
      'basename'=>$gname,
      'bargraphs'=>$bgs
   );
   $graphurl = showGenericMultiPlot($goutdir, $goutpath, $multibar, $debug);
   $out['img_url'] = $graphurl;
   return $out;
}


?>
